from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework.views import APIView
from apps.cart.models import Cart
from apps.cart.serializers import CartSerializer, CartDetailSerializer
from utils import ResponseMessage


class CartAPIView(APIView):
    # 购物车应该在登录之后，才可以访问

    # 购物车数据插入、更新和修改post请求接口
    def post(self, request):
        request_data = request.data
        if not request.user.get("status"):
            return JsonResponse(request.user, safe=False)
        print(request.user)
        mobile = request.user.get("data").get("username")
        request_data["mobile"] = mobile
        sku_id = request_data.get('sku_id')
        nums = request_data.get('nums')
        is_delete = request_data.get('is_delete')

        # 判断一下数据是否存在, 如果存在就更新，如果不存在那就插入
        data_exist = Cart.objects.filter(
            mobile=mobile,
            is_delete=0,
            sku_id=sku_id,
        )
        print(data_exist.exists())
        # 存在就更新
        if data_exist.exists():
            exist_cart_data = data_exist.get(
                mobile=mobile,
                is_delete=0,
                sku_id=sku_id,
            )
            if is_delete == 0:
                new_nums = nums + exist_cart_data.nums
                request_data["nums"] = new_nums
            elif is_delete == 1:
                request_data["nums"] = exist_cart_data.nums
            # 反序列化
            cart_ser = CartSerializer(data=request_data)
            # 验证数据
            cart_ser.is_valid(raise_exception=True)
            # 更新
            Cart.objects.filter(
                mobile=mobile,
                is_delete=0,
                sku_id=sku_id,
            ).update(**cart_ser.data)
            if is_delete == 0:
                return ResponseMessage.CartResponse.success("更新成功")
            elif is_delete == 1:
                return ResponseMessage.CartResponse.success("删除成功")
        else:
            # 这里是数据插入逻辑
            # print("++++++++++", request.data)
            cart_ser = CartSerializer(data=request_data)
            # 验证数据
            cart_ser.is_valid(raise_exception=True)
            # print("========", cart_ser)
            Cart.objects.create(**cart_ser.data)
            return ResponseMessage.CartResponse.success("添加成功")

    # 购物车数据查询get请求
    def get(self, request):
        if not request.user.get("status"):
            return JsonResponse(request.user, safe=False)
        email = request.GET.get('email')
        cart_result = Cart.objects.filter(email=email, is_delete=0)
        cart_ser = CartSerializer(instance=cart_result, many=True)
        # return JsonResponse(cart_ser.data, safe=False)
        return ResponseMessage.CartResponse.success(cart_ser.data)


# 使用序列化器,达到多表关联查询的目的
class CartDetailAPIView(APIView):
    def post(self, request):
        # if not request.user.get("status"):
        #     return JsonResponse(request.user, safe=False)
        print(request.data)
        mobile = request.user.get("data").get("username")
        filters = {
            # "mobile": "15096962415",
            "mobile": mobile,
            "is_delete": 0
        }
        shopping_cart = Cart.objects.filter(**filters).all()
        # print(shopping_cart)
        db_data = CartDetailSerializer(shopping_cart, many=True)
        return ResponseMessage.CartResponse.success(db_data.data)


# 更新购物车商品数量
class UpdateCartNumAPIView(APIView):
    def post(self, request):
        # 从token中获取这个mobile
        if not request.user.get("status"):
            return JsonResponse(request.user, safe=False)
        print(request.user)
        mobile = request.user.get("data").get("username")
        request_data = request.data
        Cart.objects.filter(
            mobile=mobile,
            sku_id=request_data["sku_id"],
            is_delete=0
        ).update(nums=request_data["nums"])
        return ResponseMessage.CartResponse.success("ok")


# 获取购物车商品数量的接口
class CartCountAPIView(APIView):
    def post(self, request):
        # 从token中获取这个mobile
        if not request.user.get("status"):
            return JsonResponse(request.user, safe=False)
        print(request.user)
        from django.db.models import Sum
        mobile = request.user.get("data").get("username")
        user_cart_count = Cart.objects.filter(
            mobile=mobile,
            is_delete=0,
        ).aggregate(Sum("nums"))
        print(user_cart_count)
        return ResponseMessage.CartResponse.success(user_cart_count)


# 删除商品
class DeleteCartGoodsAPIView(APIView):
    def post(self, request):
        # 从token中获取这个mobile
        if not request.user.get("status"):
            return JsonResponse(request.user, safe=False)
        print(request.user)
        mobile = request.user.get("data").get("username")
        request_data = request.data
        Cart.objects.filter(
            mobile=mobile,
            sku_id__in=request_data,
            is_delete=0
        ).update(is_delete=1)
        return ResponseMessage.CartResponse.success("ok")
